package com.tajiang.business.setting.print;

import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.gprinter.aidl.GpService;
import com.gprinter.io.GpDevice;
import com.gprinter.service.GpPrintService;
import com.tajiang.business.R;
import com.tajiang.business.bluetooth.PrinterConnectActivity;
import com.tajiang.business.bluetooth.utils.BTPrintUtils;
import com.tajiang.business.common.activity.BaseActivity;
import com.tajiang.business.common.utils.LogUtils;
import com.tajiang.business.common.utils.SharedPreferencesUtils;
import com.tajiang.business.common.utils.ToastUtils;
import com.tajiang.business.setting.dialog.SelPrintNumberDialog;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 打印设置
 */
public class PrintSettingActivity extends BaseActivity {

    @BindView(R.id.print_setting_number)
    TextView tvNumber;

    @BindView(R.id.print_setting_sel_tools)
    TextView tvCurTools;

    @BindView(R.id.print_setting_test)
    Button btnTest;

    private boolean[] state;
    private GpService mGpService = null;
    private PrinterServiceConnection conn = null;

    public static final int REQUEST_ENABLE_BT = 2;
    public static int DEFAULT_PRINTER_NUM = 1;
    public static final String CONNECT_STATUS = "connect.status";
    public int printNumber = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    protected void onResume(){
        super.onResume();

        getConnectState();
        updateViewState();
    }

    @Override
    protected void initTopBar() {
        setTitle("打印设置");
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_print_setting);
        connection();
    }

    @Override
    protected void initData() {

        printNumber =  Integer.parseInt(SharedPreferencesUtils.get(SharedPreferencesUtils.PRINT_AMOUNT, "1").toString());
        tvNumber.setText(printNumber + "份/单");
    }

    //选择蓝牙打印机
    @OnClick(R.id.print_setting_sel_tools_layout)
    public void sel_print_tools(){
        openChoosePrinter();
    }

    @OnClick(R.id.print_setting_number_layout)
    public void sel_number(){

        SelPrintNumberDialog.showDialog(this, new SelPrintNumberDialog.DialogCallback() {

            @Override
            public void callback(int position, String number) {

                tvNumber.setText(number + "份/单");
                SharedPreferencesUtils.put(SharedPreferencesUtils.PRINT_AMOUNT, number);
            }
        });
    }

    //打印测试
    @OnClick(R.id.print_setting_test)
    public void print_test(){

        BTPrintUtils.printTest();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && data != null) {

            Bundle bundle = data.getExtras();
            if (bundle != null) {
//                boolean isConnected = bundle.getBoolean("tv_device_connected", false);
                state = getConnectState();
                updateViewState();
            }
        }
    }

    class PrinterServiceConnection implements ServiceConnection {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            LogUtils.i("ServiceConnection", "onServiceDisconnected() called");
            mGpService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mGpService = GpService.Stub.asInterface(service);
            state = getConnectState();
//            updateViewState();
        }
    }

    private void updateViewState() {

        if (BTPrintUtils.mConnectState == 1) {//state[0] == true
            tvCurTools.setText("已连接");
            btnTest.setClickable(true);
            btnTest.setBackgroundResource(R.drawable.shape_radius_order_main_color);
        } else {
            tvCurTools.setText("未连接");
            btnTest.setClickable(false);
            btnTest.setBackgroundResource(R.drawable.shape_radius_order_gray_color);
        }
    }

    public boolean[] getConnectState() {

        if(mGpService == null){
            return null;
        }

        boolean[] state = new boolean[GpPrintService.MAX_PRINTER_CNT];
        for (int i = 0; i < DEFAULT_PRINTER_NUM; i++) {
            state[i] = false;
        }
        for (int i = 0; i < DEFAULT_PRINTER_NUM; i++) {

            try {
                if (mGpService.getPrinterConnectStatus(i) == GpDevice.STATE_CONNECTED) {
                    state[i] = true;
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        return state;
    }

    private void connection() {

        conn = new PrinterServiceConnection();
        Intent intent = new Intent(this, GpPrintService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE); // bindService
    }

    /**
     * 打开蓝牙连接和搜索页面
     */
    public void openChoosePrinter() {

        if (mGpService == null) {
            Toast.makeText(this, "Print Service is not start, please check it", Toast.LENGTH_SHORT).show();
            return;
        }
        if (checkBlueTooth()) {
            Intent intent = new Intent();
            intent.putExtra(CONNECT_STATUS, state[0]);
            intent2ActivityWidthExtrasAndForResult(intent, PrinterConnectActivity.class, 0);
        }
    }

    /**
     * 再次检查蓝牙是否开启（可用）
     *
     * @return
     */
    private boolean checkBlueTooth() {
        // Get local Bluetooth adapter
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // If the adapter is null, then Bluetooth is not supported
        if (bluetoothAdapter == null) {
            ToastUtils.showShort("蓝牙设备不可用！");
            return false;
        } else {
            // If BT is not on, request that it be enabled.
            // setupChat() will then be called during onActivityResult
            if (!bluetoothAdapter.isEnabled()) {
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        LogUtils.e("onDestroy");
        super.onDestroy();
        if (conn != null) {
            unbindService(conn); // unBindService
        }
    }

}
